package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.bizcore.activiti.dto.WorkorderDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.anhui.itsm.WorkflowBean;
import com.neusoft.neuiotms.dcam.fixed.service.ItsmService;
import com.neusoft.neuiotms.dcam.workflow.converter.ProcessApproveConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.ProcessApproveDTO;
import com.neusoft.neuiotms.dcam.workflow.model.LingyongItemKJ;
import com.neusoft.neuiotms.dcam.workflow.model.LingyongKJ;
import com.neusoft.neuiotms.dcam.workflow.model.ProcessApprove;
import com.neusoft.neuiotms.dcam.workflow.repository.LingyongKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.ProcessApproveRepository;
import com.neusoft.neuiotms.dcam.workflow.service.BaofeiSLService;
import com.neusoft.neuiotms.dcam.workflow.service.DiaoboSLService;
import com.neusoft.neuiotms.dcam.workflow.service.GuihuanSLService;
import com.neusoft.neuiotms.dcam.workflow.service.JieyongSLService;
import com.neusoft.neuiotms.dcam.workflow.service.LingyongSLService;
import com.neusoft.neuiotms.dcam.workflow.service.ProcessApproveService;
import com.neusoft.neuiotms.dcam.workflow.service.RukuSLService;
import com.neusoft.neuiotms.dcam.workflow.service.TuikuSLService;
import com.neusoft.neuiotms.dcam.workflow.service.ZhuanyiSLService;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ProcessApproveServiceImpl implements ProcessApproveService {

    @Autowired
    private ProcessApproveRepository processApproveRepository;

    @Autowired
    private ProcessApproveConverter processApproveConverter;

    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ItsmService itsmService;
    @Autowired
    private LingyongKJRepository lingyongKJRepository;
    @Autowired
    private BaofeiSLService baofeiSLService;
    @Autowired
    private TuikuSLService tuikuSLService;
    @Autowired
    private ZhuanyiSLService zhuanyiSLService;
    @Autowired
    private DiaoboSLService diaoboSLService;
    @Autowired
    private GuihuanSLService guihuanSLService;
    @Autowired
    private LingyongSLService lingyongSLService;
    @Autowired
    private JieyongSLService jieyongSLService;
    @Autowired
    private RukuSLService rukuSLService;

    @Override
    @Transactional
    public ProcessApproveDTO create(final ProcessApproveDTO dto, final UserBean user) {
        this.processInstanceService.setGlobalVariable(dto.getTaskId(), "opinion",
                dto.getOpinion());

        // 查询当前workNum和TaskId下是否存在记录
        final ProcessApprove oldModel = this.processApproveRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), dto.getTaskId());
        if (oldModel == null) { // 如果不存在新增
            dto.setId(null);
        }

        final ProcessApprove model = this.processApproveConverter.toModel(dto);
        this.processApproveRepository.save(model);

        // 完成节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        final WorkorderDTO workorderDTO = this.workOrderService.details(dto.getWorkOrderNum());

        // 科技领用
        if ("LingyongKJ".equals(workorderDTO.getType()) && "PASS".equalsIgnoreCase(dto.getOpinion())) {
            // 固定资产和消耗品领用都推送ITSM审批
            // if ("1".equals(dto.getCategories())) {
            try {
                // 对接ITSM
                final List<WorkflowBean.AssetBean> assetList = Lists.newArrayList();

                final LingyongKJ lingyongKJModel =
                        this.lingyongKJRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());

                for (final LingyongItemKJ item : lingyongKJModel.getRecipientRequires()) {
                    final WorkflowBean.AssetBean assetBean = WorkflowBean.AssetBean.builder()
                            .assetClassID(item.getSmallTypeCode())
                            .assetModel(item.getSpecifications())
                            .assetUnit("未知")
                            .assetPrice(0)
                            .assetNumber(item.getQuantity())
                            .assetName(item.getSmallTypeName())
                            .assetType("1")
                            .assetSign("未知")
                            .build();
                    assetList.add(assetBean);
                }

                final WorkflowBean workflowBean = WorkflowBean.builder()
                        .workNum(dto.getWorkOrderNum())
                        .workName("设备领用")
                        .workType("20")
                        .workContent("设备领用申请")
                        .applyUser(lingyongKJModel.getCreateUser())
                        .assetList(assetList)
                        .build();

                this.itsmService.pushItsm(workflowBean);
            } catch (final Exception e) {
                ProcessApproveServiceImpl.log.error("设备领用流程推送ITSM时发生错误", e);
            }
            // }
        }

        // 总行报废
        if ("BaofeiSL".equals(workorderDTO.getType()) && "PASS".equalsIgnoreCase(dto.getOpinion())) {
            this.baofeiSLService.baofeiSLCompleteUpdate(dto.getWorkOrderNum());
        }

        // 总行退库
        if ("TuikuSL".equals(workorderDTO.getType()) && "PASS".equalsIgnoreCase(dto.getOpinion())) {
            this.tuikuSLService.processEnd(dto.getWorkOrderNum());
        }

        // 总行转移
        if ("ZhuanyiSL".equals(workorderDTO.getType()) && "PASS".equalsIgnoreCase(dto.getOpinion())) {
            this.zhuanyiSLService.processEnd(dto.getWorkOrderNum());
        }

        // 总行调拨
        if ("DiaoboSL".equals(workorderDTO.getType()) && "PASS".equalsIgnoreCase(dto.getOpinion())) {
            this.diaoboSLService.processEnd(dto.getWorkOrderNum());
        }

        // 总行归还
        if ("GuihuanSL".equals(workorderDTO.getType()) && "PASS".equalsIgnoreCase(dto.getOpinion())) {
            this.guihuanSLService.processEnd(dto.getWorkOrderNum());
        }

        // 总行借用
        if ("JieyongSL".equals(workorderDTO.getType()) && "REJECT".equalsIgnoreCase(dto.getOpinion())) {
            this.jieyongSLService.reject(dto.getWorkOrderNum());
        }

        // 总行领用
        if ("LingyongSL".equals(workorderDTO.getType()) && "REJECT".equalsIgnoreCase(dto.getOpinion())) {
            this.lingyongSLService.reject(dto.getWorkOrderNum());
        }

        // 总行入库
        if ("RukuSL".equals(workorderDTO.getType()) && "PASS".equalsIgnoreCase(dto.getOpinion())) {
            this.rukuSLService.processEnd(dto.getWorkOrderNum());
        }

        return this.processApproveConverter.toDTO(model);

    }

    @Override
    public ProcessApproveDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        ProcessApprove model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.processApproveRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ProcessApproveDTO();
                    } else {
                        model = this.processApproveRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model = this.processApproveRepository.findByWorkOrderNum(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.processApproveConverter.toDTO(model);

    }

    @Override
    public ProcessApproveDTO findByWorkOrderNumAndTaskId(final String workOrderNum, final String taskId) {
        final ProcessApprove model =
                this.processApproveRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
        return this.processApproveConverter.toDTO(model);

    }

    @Override
    public void deleteByWorkOrderNum(final String workOrderNum) {
        this.processApproveRepository.deleteByWorkOrderNum(workOrderNum);
    }

}
